package com.cheer.ba.view.activity;

import android.content.Intent;
import android.os.CountDownTimer;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.text.Editable;
import android.text.InputType;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.text.method.DigitsKeyListener;
import android.text.method.HideReturnsTransformationMethod;
import android.text.method.PasswordTransformationMethod;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bigkoo.svprogresshud.SVProgressHUD;
import com.cheer.ba.R;
import com.cheer.ba.app.App;
import com.cheer.ba.constant.CodeStatus;
import com.cheer.ba.constant.Constants;
import com.cheer.ba.constant.H5Address;
import com.cheer.ba.constant.IntentCode;
import com.cheer.ba.constant.IntentKey;
import com.cheer.ba.constant.Type;
import com.cheer.ba.model.UserInfoModel;
import com.cheer.ba.presenter.impl.LoginPresenter;
import com.cheer.ba.service.BackGroundService;
import com.cheer.ba.utils.NetUtils;
import com.cheer.ba.utils.StringUtils;
import com.cheer.ba.utils.TextViewUtils;
import com.cheer.ba.utils.ToastUtil;
import com.cheer.ba.view.base.BaseCommAty;
import com.litesuits.common.utils.HexUtil;
import com.litesuits.common.utils.MD5Util;

import org.json.JSONException;
import org.json.JSONObject;

import butterknife.BindView;
import butterknife.OnClick;
import cn.smssdk.EventHandler;
import cn.smssdk.SMSSDK;

/**
 * 注册界面
 *
 * @author HQ
 *         created at 2017/3/6 0006 15:16
 */
public class RegisterAty extends BaseCommAty {

    //手机号
    @BindView(R.id.id_regist_phone_edit)
    EditText mEditPhone;
    private String mPhone = "";
    @BindView(R.id.id_clear_phone)
    ImageView mImgClearPhone;

    //发送验证码
    @BindView(R.id.id_regist_send_sms_btn)
    Button mBtnSendCode;

    //验证码
    @BindView(R.id.id_regist_code_edit)
    EditText mEditCode;
    private String mCode = "";
    @BindView(R.id.id_clear_code)
    ImageView mImgClearCode;

    //密码
    @BindView(R.id.id_regist_pw_edit)
    EditText mEditPassw;
    private String mPassw = "";
    @BindView(R.id.id_clear_pw)
    ImageView mImgClearPw;
    @BindView(R.id.id_watch_pass)
    ImageView mImgWatchPw;

    //再次输入密码
    @BindView(R.id.id_regist_re_pw_edit)
    EditText mEditRePassw;
    private String mRePassw = "";
    @BindView(R.id.id_clear_re_pw)
    ImageView mImgClearRePw;
    @BindView(R.id.id_watch_re_pass)
    ImageView mImgWatchRePw;

    //注册频道
    @BindView(R.id.id_regist_channel_edit)
    EditText mEditChannel;
    private String mChannel = "";
    @BindView(R.id.id_clear_channel)
    ImageView mImgClearChannel;

    //邀请人会员号
    @BindView(R.id.id_regist_member_edit)
    EditText mEditMember;
    private String mMember = "";
    @BindView(R.id.id_clear_member)
    ImageView mImgClearMember;

    //是否显示同意条款
    @BindView(R.id.id_regist_agree_ll)
    RelativeLayout mAgreeLL;

    //同意条款
    @BindView(R.id.id_regist_checkbox)
    CheckBox mCheckBox;

    /**
     * 条款
     */
    @BindView(R.id.find_pass2_protocol)
    TextView mTvProtocol;

    /**
     * 倒计时类
     */
    private MyCount mc;

    private static final int SUBMIT_VERIFICATION_CODE_COMPLETE = 1;
    private static final int GET_VERIFICATION_CODE_COMPLETE = 2;
    private static final int RESULT_ERROR = 3;
    //获取验证码太频繁
    private static final int RESULT_ERROR_1 = 4;
    //获取验证码失败
    private static final int RESULT_ERROR_2 = 5;
    //提交验证失败
    private static final int RESULT_ERROR_3 = 6;

    /**
     * 短信回调
     */
    private EventHandler en = new EventHandler() {
        @Override
        public void afterEvent(int event, int result, Object data) {
            Log.d("huangqiang", event + "---" + result + "===" + data.toString());
            //解析注册结果
            if (result == SMSSDK.RESULT_COMPLETE) {
                //回调完成
                if (event == SMSSDK.EVENT_SUBMIT_VERIFICATION_CODE) {
                    //提交验证码成功
                    handler.sendEmptyMessage(GET_VERIFICATION_CODE_COMPLETE);
                } else if (event == SMSSDK.EVENT_GET_VERIFICATION_CODE) {
                    //获取验证码成功
                    handler.sendEmptyMessage(SUBMIT_VERIFICATION_CODE_COMPLETE);
                } else if (event == SMSSDK.EVENT_GET_SUPPORTED_COUNTRIES) {
                    //返回支持发送验证码的国家列表
                }
            } else if (result == SMSSDK.RESULT_ERROR) {
                if (null == data) {
                    handler.sendEmptyMessage(RESULT_ERROR_1);
                    return;
                }
                //处理失败结果
                Throwable throwable = (Throwable) data;
                throwable.printStackTrace();
                JSONObject object;
                try {
                    object = new JSONObject(throwable.getMessage());
                    // 错误代码
                    int status = object.optInt("status");
                    // 错误描述
                    String detail = object.optString("detail");
                    if (status == 468) {
                        handler.sendEmptyMessage(RESULT_ERROR_3);
                    } else {
                        handler.sendEmptyMessage(RESULT_ERROR_2);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                    handler.sendEmptyMessage(RESULT_ERROR_1);
                }
            }
        }
    };

    private Handler handler = new Handler() {
        public void handleMessage(android.os.Message msg) {
            switch (msg.what) {
                case SUBMIT_VERIFICATION_CODE_COMPLETE:
                    ToastUtil.showToast("获取成功");
                    break;
                case GET_VERIFICATION_CODE_COMPLETE:
//                    ToastUtil.showToast("提交验证成功");
                    //注册手机号
                    ((LoginPresenter) presenter).registerUser(mPhone, HexUtil.encodeHexStr(MD5Util.md5(mPassw)), mCode, mChannel, mMember);
                    break;
                case RESULT_ERROR_1:
                    SVProgressHUD.showInfoWithStatus(aty, getString(R.string.get_more_code));
                    break;
                case RESULT_ERROR_2:
                    SVProgressHUD.showInfoWithStatus(aty, getString(R.string.get_code_error));
                    handlerByPage(CodeStatus.Gegeneral.ERROR_DATA, CodeStatus.Gegeneral.ERROR_DATA, getString(R.string.get_code_error));
                    break;
                case RESULT_ERROR_3:
                    SVProgressHUD.showInfoWithStatus(aty, getString(R.string.check_code_fail));
                    break;
            }
        }
    };

    @Nullable
    @Override
    public View loadView(LayoutInflater inflater, View childView) {
        return super.loadView(inflater, inflater.inflate(R.layout.aty_register, null));
    }

    @Override
    public void initPresenter() {
        presenter = new LoginPresenter();
    }

    @Override
    public boolean hasDataInPage() {
        return true;
    }

    @Override
    public void initView() {
        setTitleText(getString(R.string.register_title));
        if (BackGroundService.time_code != 0) {
            startCount(BackGroundService.time_code);
        }
        TextViewUtils.getInstance(getString(R.string.register_protocol));
        TextViewUtils.setTxtIndex(8, 14, new TextViewUtils.TextViewOnClickListener() {
            @Override
            public void onTextClick(View view) {

            }
        });
        TextViewUtils.setSpannableStyle(mTvProtocol);
    }

    @Override
    public void initData() {
//        SMSSDK.registerEventHandler(en);
        mEditPhone.addTextChangedListener(new TextWatcher() {
            @Override
            public void onTextChanged(CharSequence s, int arg1, int arg2,
                                      int arg3) {
                updateEtInfo();
                if (!StringUtils.isEmpty(mPhone)) {
                    mImgClearPhone.setVisibility(View.VISIBLE);
                } else {
                    mImgClearPhone.setVisibility(View.GONE);
                }
            }

            @Override
            public void beforeTextChanged(CharSequence arg0, int arg1,
                                          int arg2, int arg3) {
            }

            @Override
            public void afterTextChanged(Editable arg0) {
            }
        });
        mEditCode.addTextChangedListener(new TextWatcher() {
            @Override
            public void onTextChanged(CharSequence s, int arg1, int arg2,
                                      int arg3) {
                updateEtInfo();
                if (!StringUtils.isEmpty(mCode)) {
                    mImgClearCode.setVisibility(View.VISIBLE);
                } else {
                    mImgClearCode.setVisibility(View.GONE);
                }
            }

            @Override
            public void beforeTextChanged(CharSequence arg0, int arg1,
                                          int arg2, int arg3) {
            }

            @Override
            public void afterTextChanged(Editable arg0) {
            }
        });
        mEditPassw.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                updateEtInfo();
                if (!StringUtils.isEmpty(mPassw)) {
                    mImgClearPw.setVisibility(View.VISIBLE);
                } else {
                    mImgClearPw.setVisibility(View.GONE);
                }
            }

            @Override
            public void afterTextChanged(Editable editable) {
            }
        });
        mEditPassw.setKeyListener(new DigitsKeyListener() {
            @Override
            public int getInputType() {
                return InputType.TYPE_TEXT_VARIATION_PASSWORD;
            }

            @Override
            protected char[] getAcceptedChars() {
                char[] data = getResources().getString(
                        R.string.edit_only_can_input).toCharArray();
                return data;
            }
        });

        mEditRePassw.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                updateEtInfo();
                if (!StringUtils.isEmpty(mRePassw)) {
                    mImgClearRePw.setVisibility(View.VISIBLE);
                } else {
                    mImgClearRePw.setVisibility(View.GONE);
                }
            }

            @Override
            public void afterTextChanged(Editable editable) {
            }
        });
        mEditRePassw.setKeyListener(new DigitsKeyListener() {
            @Override
            public int getInputType() {
                return InputType.TYPE_TEXT_VARIATION_PASSWORD;
            }

            @Override
            protected char[] getAcceptedChars() {
                char[] data = getResources().getString(
                        R.string.edit_only_can_input).toCharArray();
                return data;
            }
        });
        mEditChannel.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
                updateEtInfo();
                if (!StringUtils.isEmpty(mChannel)) {
                    mImgClearChannel.setVisibility(View.VISIBLE);
                } else {
                    mImgClearChannel.setVisibility(View.GONE);
                }
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
        mEditMember.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
                updateEtInfo();
                if (!StringUtils.isEmpty(mMember)) {
                    mImgClearMember.setVisibility(View.VISIBLE);
                } else {
                    mImgClearMember.setVisibility(View.GONE);
                }
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });

        String phone = getIntent().getStringExtra(IntentKey.General.KEY_DES);
        if (!StringUtils.isEmpty(phone)) {
            mEditPhone.setText(phone);
        }
    }

    /**
     * 获得输入数据
     */
    private void updateEtInfo() {
        mPhone = mEditPhone.getText().toString().trim();
        mCode = mEditCode.getText().toString().trim();
        mPassw = mEditPassw.getText().toString().trim();
        mRePassw = mEditRePassw.getText().toString().trim();
        mChannel = mEditChannel.getText().toString().trim();
        mMember = mEditMember.getText().toString().trim();
    }

    /**
     * 启动倒计时
     */
    private void startCount(long time) {
        mBtnSendCode.setEnabled(false);
        if (null != mc) {
            mc.cancel();
            mc = null;
        }
        mc = new MyCount(time, 1000);
        mc.start();
    }


    /**
     * 倒计时类
     */
    public class MyCount extends CountDownTimer {
        public MyCount(long millisInFuture, long countDownInterval) {
            super(millisInFuture, countDownInterval);
        }

        @Override
        public void onTick(long millisUntilFinished) {
            mBtnSendCode.setText(millisUntilFinished / 1000
                    + getString(R.string.regist_second));
        }

        @Override
        public void onFinish() {
            mBtnSendCode.setText(getString(R.string.send_check_code));
            mBtnSendCode.setEnabled(true);
        }
    }

    /**
     * 检查输入信息格式是否正确
     *
     * @return
     */
    public boolean checkData() {
        updateEtInfo();
        if (mCheckBox.isChecked()) {
            if (StringUtils.isMobile(mPhone)) {
                if (StringUtils.isEmpty(mCode)) {
                    SVProgressHUD.showInfoWithStatus(aty, getString(R.string.input_check_code));
                } else {
                    if (StringUtils.isEmpty(mPassw) || mPassw.length() > 18 || mPassw.length() < 6) {
                        SVProgressHUD.showInfoWithStatus(aty, getString(R.string.setting_login_pwd));
                    } else {
                        if (StringUtils.isNumRic(mPassw) || StringUtils.isLetterRic(mPassw)) {
                            SVProgressHUD.showInfoWithStatus(aty, getString(R.string.pw_had_num_letter));
                        } else {
                            if (TextUtils.equals(mPassw, mRePassw)) {
                                return true;
                            } else {
                                SVProgressHUD.showInfoWithStatus(aty, "两次输入密码不一致");
                            }
                        }
                    }
                }
            } else {
                SVProgressHUD.showInfoWithStatus(aty, getString(R.string.phone_error));
            }
        } else {
            SVProgressHUD.showInfoWithStatus(aty, getString(R.string.no_choose_protocol));
        }
        return false;
    }

    @OnClick({R.id.id_clear_channel, R.id.id_clear_member, R.id.id_regist_send_sms_btn, R.id.id_watch_pass, R.id.id_watch_re_pass, R.id.id_clear_phone, R.id.id_clear_code, R.id.id_clear_pw, R.id.id_regist_btn, R.id.find_pass2_protocol})
    public void onClick(View view) {
        switch (view.getId()) {
            //注册频道
            case R.id.id_clear_channel:
                mEditChannel.setText("");
                break;
            //邀请人会员号
            case R.id.id_clear_member:
                mEditMember.setText("");
                break;
            //发送手机验证码
            case R.id.id_regist_send_sms_btn:
                if (!StringUtils.isMobile(mPhone)) {
                    SVProgressHUD.showInfoWithStatus(aty, getString(R.string.phone_error));
                    return;
                }
                if (!NetUtils.isNetworkConnected(aty)) {
                    SVProgressHUD.showInfoWithStatus(aty, getString(R.string.no_net_work));
                } else {
                    BackGroundService.countDownCode(Constants.COUNTDOWN * 1000);
                    startCount(Constants.COUNTDOWN * 1000);
                    ((LoginPresenter) presenter).getVeriCode(mPhone, Type.VERIFY_CODE, "");
                    //获取短信验证码
//                    SMSSDK.getVerificationCode("86", mPhone);
                }
                break;
            //密码显示隐藏按钮
            case R.id.id_watch_pass:
                int length = TextUtils.isEmpty(mEditPassw.getText()) ? 0 : mEditPassw.getText().length();
                if (mEditPassw.getTransformationMethod() == PasswordTransformationMethod.getInstance()) {
                    mEditPassw.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
                    mImgWatchPw.setImageDrawable(getResources().getDrawable(R.drawable.ic_eye_on));
                } else {
                    mEditPassw.setTransformationMethod(PasswordTransformationMethod.getInstance());
                    mImgWatchPw.setImageDrawable(getResources().getDrawable(R.drawable.ic_eye_off));
                }
                mEditPassw.setSelection(length);
                break;
            //密码显示隐藏按钮
            case R.id.id_watch_re_pass:
                int length1 = TextUtils.isEmpty(mEditRePassw.getText()) ? 0 : mEditRePassw.getText().length();
                if (mEditRePassw.getTransformationMethod() == PasswordTransformationMethod.getInstance()) {
                    mEditRePassw.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
                    mImgWatchRePw.setImageDrawable(getResources().getDrawable(R.drawable.ic_eye_on));
                } else {
                    mEditRePassw.setTransformationMethod(PasswordTransformationMethod.getInstance());
                    mImgWatchRePw.setImageDrawable(getResources().getDrawable(R.drawable.ic_eye_off));
                }
                mEditRePassw.setSelection(length1);
                break;
            case R.id.id_clear_phone:
                mEditPhone.setText("");
                break;
            case R.id.id_clear_code:
                mEditCode.setText("");
                break;
            case R.id.id_clear_pw:
                mEditPassw.setText("");
                break;
            case R.id.id_clear_re_pw:
                mEditRePassw.setText("");
                break;
            //注册
            case R.id.id_regist_btn:
                if (com.cheer.ba.utils.CountDownTimer.isFastClick()) {
                    return;
                }
                if (checkData()) {
                    //提交验证
//                    SMSSDK.submitVerificationCode("86", mPhone, mCode);
                    ((LoginPresenter) presenter).registerUser(mPhone, HexUtil.encodeHexStr(MD5Util.md5(mPassw)), mCode, mChannel, mMember);
                }
                break;
            //服务条款
            case R.id.find_pass2_protocol:
                CommH5Aty.startCommonH5(aty, H5Address.USER_REGISTER, false);
                break;
        }
    }

    /**
     * 注册成功
     *
     * @author HQ
     * created at 2017/3/8 0008 14:40
     */
    @Override
    public <T> void updateView(T t) {
        if (null != t) {
            final UserInfoModel model = (UserInfoModel) t;
            new Handler().postDelayed(new Runnable() {
                @Override
                public void run() {
                    App.REGISTER_GIFT = 1;
                    Intent intent = new Intent();
                    intent.putExtra(IntentKey.General.KEY_MODEL, model);
                    setResult(IntentCode.Register.REGISTER_RESULT_CODE, intent);
                    finish();
                }
            }, 2000);
        }
    }

    /**
     * 处理接口返回数据
     *
     * @author HQ
     * created at 2017/3/8 0008 11:30
     */
    @Override
    public void handlerByPage(int flag1, int flag2, String string) {
        if (flag1 == CodeStatus.Gegeneral.DATA_SUCCESS_FULL) {
            //获取短信验证码成功

        } else if (flag1 == CodeStatus.Gegeneral.ERROR_DATA) {
            //获取短信验证码失败
            SVProgressHUD.showInfoWithStatus(aty, string);
            mBtnSendCode.setText(getString(R.string.send_check_code));
            mBtnSendCode.setEnabled(true);
            if (mc != null) {
                mc.cancel();
            }
            if (null != BackGroundService.countCode) {
                BackGroundService.countCode.cancel();
            }
            BackGroundService.time_code = 0;
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (null != mc) {
            mc.cancel();
        }
//        SMSSDK.unregisterEventHandler(en);
    }
}
